<template>
  <div class="contact-list">
    <div
        v-for="contact in contacts"
        :key="contact.id"
        class="contact-item"
        :class="{ active: isActive(contact) }"
        @click="$emit('select', contact.userId)"
    >
      <el-avatar :size="36" :src="contact.avatar" />
      <div class="contact-info">
        <div class="contact-name">{{ contact.username }}</div>
        <div class="last-message">{{ contact.lastMessage || '暂无消息' }}</div>
      </div>
      <div class="contact-meta">
        <div class="timestamp" v-if="contact.lastTime">
          {{ formatTime(contact.lastTime) }}
        </div>
        <el-badge
            v-if="contact.unread > 0"
            :value="contact.unread"
            class="unread-badge"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import { format } from 'date-fns'

export default defineComponent({
  props: {
    contacts: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'private'
    }
  },
  methods: {
    formatTime(timestamp) {
      return format(new Date(timestamp), 'HH:mm')
    },
    isActive(contact) {
      return this.$parent.activeSession?.type === this.type &&
          this.$parent.activeSession?.id === contact.id
    }
  }
})
</script>

<style scoped>
.contact-list {
  overflow-y: auto;
  flex: 1;
}

.contact-item {
  display: flex;
  padding: 12px 15px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
  transition: background-color 0.3s;
}

.contact-item:hover {
  background-color: #f5f7fa;
}

.contact-item.active {
  background-color: #e6f7ff;
}

.contact-info {
  flex: 1;
  margin-left: 12px;
  overflow: hidden;
}

.contact-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.last-message {
  font-size: 13px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.contact-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.timestamp {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.unread-badge {
  margin-top: 2px;
}
</style>